﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using BLL;
using System.IO;
using System.Text;
using System.Reflection;
using NPOI.HSSF.UserModel;
using NPOI.HPSF;
using NPOI.SS.UserModel;
using System.Data;

namespace PMS.Web
{
    public partial class ProjectMaintain : ExportFiles
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ((ScriptManager)Master.FindControl("ScriptManager1")).RegisterPostBackControl(btn_ExpotReport);
                PMS_User user = PageComm.GetUser(this.Response);
                if (PageComm.IsEdit(BLL.ActionMenu.Project, user.role))
                {
                    btn_Add.Visible = true;
                    gv_ProjectList.Columns[5].Visible = true;
                    gv_ProjectList.Columns[6].Visible = true;
                }
                if (PageComm.IsVisit(ActionMenu.Finance, user.role))
                {
                    gv_ProjectList.Columns[10].Visible = true;
                }
                hid_userID.Value = user.id.ToString();
            }
        }

        protected void ddl_ProjectType_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetProjectList();
        }

        /// <summary>
        /// 数据绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void gv_ProjectList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            GridViewRow row = e.Row;
            if (row.RowType == DataControlRowType.DataRow)
            {
                PMS_Project model = row.DataItem as PMS_Project;
                ImageButton imgbtn_Detail = row.FindControl("imgbtn_Detail") as ImageButton;
                imgbtn_Detail.Attributes.Add("onclick", "desProject('" + model.id + "');return false;");

                ImageButton imgbtn_Edit = row.FindControl("imgbtn_Edit") as ImageButton;
                imgbtn_Edit.Attributes.Add("onclick", "editProject('" + model.id + "');return false;");

                ImageButton imabtn_Delete = row.FindControl("imabtn_Delete") as ImageButton;
                imabtn_Delete.Attributes.Add("onclick", "deleteProject('" + model.id + "');return false;");

                ImageButton imgbtn_Evelve = row.FindControl("imgbtn_Evelve") as ImageButton;
                imgbtn_Evelve.Attributes.Add("onclick", "desProjectEvelve('" + model.id + "');return false;");

                ImageButton imgbtn_Renewal = row.FindControl("imgbtn_Renewal") as ImageButton;
                imgbtn_Renewal.Attributes.Add("onclick", "desProjectRenewal('" + model.id + "');return false;");

                ImageButton imgbtn_Maintain = row.FindControl("imgbtn_Maintain") as ImageButton;
                imgbtn_Maintain.Attributes.Add("onclick", "desProjectMaintain('" + model.id + "');return false;");

                ImageButton imgbtn_Finance = row.FindControl("imgbtn_Finance") as ImageButton;
                if (model.projectType == "工程项目")
                    imgbtn_Finance.Attributes.Add("onclick", "desProjectState('" + model.id + "');return false;");
                else if (model.projectType == "维保项目")
                    imgbtn_Finance.Attributes.Add("onclick", "desFinanceMaintainace('" + model.id + "');return false;");
                else
                    imgbtn_Finance.Attributes.Add("onclick", "desFinanceRenewal('" + model.id + "');return false;");
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Search_Click(object sender, EventArgs e)
        {
            GetProjectList();
        }

        /// <summary>
        /// 查询
        /// </summary>
        public void GetProjectList()
        {
            gv_ProjectList.DataSource = SelectData();
            gv_ProjectList.DataBind();
            if (ddl_ProjectType.Text == "工程项目")
            {
                gv_ProjectList.Columns[7].Visible = true;
                gv_ProjectList.Columns[8].Visible = false;
                gv_ProjectList.Columns[9].Visible = false;
            }
            else if (ddl_ProjectType.Text == "维保项目")
            {
                gv_ProjectList.Columns[9].Visible = true;
                gv_ProjectList.Columns[8].Visible = false;
                gv_ProjectList.Columns[7].Visible = true;
            }
            else
            {
                gv_ProjectList.Columns[8].Visible = true;
                gv_ProjectList.Columns[7].Visible = true;
                gv_ProjectList.Columns[9].Visible = false;
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <returns></returns>
        public List<PMS_Project> SelectData()
        {
            PMS_ProjectQuery query = new PMS_ProjectQuery();
            if (!string.IsNullOrEmpty(txt_ProjectID.Text.Trim()))
                query.projectID = Convert.ToInt32(txt_ProjectID.Text.Trim());
            if (!string.IsNullOrEmpty(txt_FromDate.Text.Trim()))
                query.startDate = Convert.ToDateTime(txt_FromDate.Text.Trim());
            if (!string.IsNullOrEmpty(txt_ToDate.Text.Trim()))
                query.endDate = Convert.ToDateTime(txt_ToDate.Text.Trim());
            query.roleID = Convert.ToInt32(hid_parentID.Value);
            query.userID = Convert.ToInt32(hid_userID.Value);
            query.projectType = ddl_ProjectType.Text;

            BLL.PMS_ProjectBLL bll = new BLL.PMS_ProjectBLL();
            BLL.PMS_RoleListBLL rbll = new BLL.PMS_RoleListBLL();
            PMS_RoleList model = rbll.GetModel(Convert.ToInt32(hid_parentID.Value));
            if (model == null)
                return null;
            string[] roleIDs = model.roleIDs.Split('|');
            if (roleIDs.Length > 1)
            {
                hid_IsCreate.Value = "1";
            }
            else
            {
                hid_IsCreate.Value = "0";
            }

            List<PMS_Project> list = bll.GetList(query);
            return list;
        }

        /// <summary>
        /// 查询导出项目的数据
        /// </summary>
        /// <returns></returns>
        public DataTable GetDataList()
        {
            PMS_ProjectQuery query = new PMS_ProjectQuery();
            if (!string.IsNullOrEmpty(txt_ProjectID.Text.Trim()))
                query.projectID = Convert.ToInt32(txt_ProjectID.Text.Trim());
            if (!string.IsNullOrEmpty(txt_FromDate.Text.Trim()))
                query.startDate = Convert.ToDateTime(txt_FromDate.Text.Trim());
            if (!string.IsNullOrEmpty(txt_ToDate.Text.Trim()))
                query.endDate = Convert.ToDateTime(txt_ToDate.Text.Trim());
            query.roleID = Convert.ToInt32(hid_parentID.Value);
            query.userID = Convert.ToInt32(hid_userID.Value);
            query.projectType = ddl_ProjectType.Text;

            BLL.PMS_ProjectBLL bll = new BLL.PMS_ProjectBLL();
            BLL.PMS_RoleListBLL rbll = new BLL.PMS_RoleListBLL();
            PMS_RoleList model = rbll.GetModel(Convert.ToInt32(hid_parentID.Value));
            if (model == null)
                return null;
            string[] roleIDs = model.roleIDs.Split('|');
            if (roleIDs.Length > 1)
            {
                hid_IsCreate.Value = "1";
            }
            else
            {
                hid_IsCreate.Value = "0";
            }

            DataTable dtshow = bll.GetListTable(query);
            return dtshow;
        }

        /// <summary>
        /// 项目报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_ProjectReport_Click(object sender, EventArgs e)
        {
            DataTable dtshow = GetDataList();
            if (dtshow != null && dtshow.Rows.Count > 0)
            {
                string projectType = ddl_ProjectType.Text;
                ExportExcel(projectType, dtshow);
            }
        }

        /// <summary>
        /// 清单报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_ReportList_Click(object sender, EventArgs e)
        {
            DataTable dtshow = GetDataList();
            if (dtshow != null && dtshow.Rows.Count > 0)
            {
                string projectType = ddl_ProjectType.Text;
                ExportExcel(projectType + "清单", dtshow);
            }
        }

        /// <summary>
        /// 财务报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_Finance_Click(object sender, EventArgs e)
        {
            DataTable dtshow = GetDataList();
            if (dtshow != null && dtshow.Rows.Count > 0)
            {
                string projectType = ddl_ProjectType.Text;
                ExportExcel(projectType + "财务", dtshow);
            }
        }

        /// <summary>
        /// 导出项目报表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btn_ExpotReport_Click(object sender, EventArgs e)
        {
            DataTable dtshow = GetDataList();
            if (dtshow != null && dtshow.Rows.Count > 0)
            {
                string projectType = ddl_ProjectType.Text;
                ExportExcel(projectType, dtshow);
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sheetName">Excel文件名</param>
        /// <param name="dtshow">数据集</param>
        public void ExportExcelS(string sheetName, DataTable dtshow)
        {
            string filename = HttpUtility.UrlEncode(sheetName + DateTime.Now.ToString("yyyy-MM-dd") + ".xls", Encoding.GetEncoding("utf-8")).ToString();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename));
            Response.Clear();

            InitializeWorkbook();
            GenerateData(dtshow, sheetName);
            
            Response.BinaryWrite(WriteToStream().GetBuffer());
            Response.End();
        }

        
        HSSFWorkbook hssfworkbook;
        void InitializeWorkbook()
        {
            hssfworkbook = new HSSFWorkbook();

            ////create a entry of DocumentSummaryInformation
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "NPOI Team";
            hssfworkbook.DocumentSummaryInformation = dsi;

            ////create a entry of SummaryInformation
            SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "NPOI SDK Example";
            hssfworkbook.SummaryInformation = si;
        }

        MemoryStream WriteToStream()
        {
            //Write the stream data of workbook to the root directory
            MemoryStream file = new MemoryStream();
            hssfworkbook.Write(file);
            return file;
        }

        void GenerateData(DataTable dtshow, string sheetName)
        {
            //获取模版
            List<Templete> excelList = BLL.TempleteBLL.GetTemplete(sheetName);
            Sheet sheet1 = hssfworkbook.CreateSheet(sheetName);

            #region 列设置

            //设置字体
            Font font0 = hssfworkbook.CreateFont();
            font0.Boldweight = 700;

            //居中设置
            CellStyle cellstyle0 = hssfworkbook.CreateCellStyle();
            cellstyle0.Alignment = HorizontalAlignment.CENTER;
            cellstyle0.BorderBottom = CellBorderType.THIN;
            cellstyle0.BorderLeft = CellBorderType.THIN;
            cellstyle0.BorderRight = CellBorderType.THIN;
            cellstyle0.BorderTop = CellBorderType.THIN;
            cellstyle0.SetFont(font0);

            //居右设置
            CellStyle cellstyle1 = hssfworkbook.CreateCellStyle();
            cellstyle1.Alignment = HorizontalAlignment.RIGHT;
            cellstyle1.BorderBottom = CellBorderType.THIN;
            cellstyle1.BorderLeft = CellBorderType.THIN;
            cellstyle1.BorderRight = CellBorderType.THIN;
            cellstyle1.BorderTop = CellBorderType.THIN;

            //居左设置
            CellStyle cellstyle2 = hssfworkbook.CreateCellStyle();
            cellstyle2.Alignment = HorizontalAlignment.LEFT;
            cellstyle2.BorderBottom = CellBorderType.THIN;
            cellstyle2.BorderLeft = CellBorderType.THIN;
            cellstyle2.BorderRight = CellBorderType.THIN;
            cellstyle2.BorderTop = CellBorderType.THIN;

            #endregion

            Row row0 = sheet1.CreateRow(0);
            //表头设置
            for (int i = 0; i < excelList.Count; i++)
            {
                row0.CreateCell(i).SetCellValue(excelList[i].columnName);
                //sheet1.SetColumnWidth(i, excelList[i].columnWidth);
                row0.GetCell(i).CellStyle = cellstyle0;
            }

            //数据绑定
            for (int i = 0; i < dtshow.Rows.Count; i++)
            {
                Row row = sheet1.CreateRow(i + 1);
                for (int j = 0; j < excelList.Count; j++)
                {
                    #region 数据绑定
                    string columnName = excelList[j].columnName + "";
                    string dataName = excelList[j].dataName + "";
                    string formatStr = excelList[j].formatStr + "";
                    object result = dtshow.Rows[i][dataName];
                    if (!string.IsNullOrEmpty(formatStr))
                    {
                        result = string.Format(formatStr, result);
                    }

                    if (columnName == "序号")
                    {
                        result = (i + 1).ToString();
                    }
                    row.CreateCell(j).SetCellValue(result.ToString());
                    #endregion
                }
            }
        }
    }
}